<template>
  <BaseContainer>
    <QueryFilter
      :label-col="{ style: { width: '70px' } }"
      :model="queryFields"
      @submit="queryOrderList"
      @reset="resetOrderList"
    >
      <a-form-item name="orderNo" label="词包ID">
        <a-input v-model:value.trim="queryFields.orderId" placeholder="请输入词包ID" allow-clear />
      </a-form-item>
      <a-form-item name="keyword" label="关键词">
        <a-input placeholder="请输入准确的关键词" allow-clear v-model:value.trim="queryFields.keyword"></a-input>
      </a-form-item>
      <a-form-item label="审核状态">
        <a-select
          v-model:value="queryFields.serviceApproveStatus"
          placeholder="请选择审核状态"
          :options="approveStatusOptions"
        />
      </a-form-item>
      <a-form-item label="上线状态">
        <a-select
          v-model:value="queryFields.serviceStatus"
          placeholder="请选择上线状态"
          :options="serviceStatusOptions"
        />
      </a-form-item>
      <a-form-item name="customerId" label="客户id" v-if="hasPermission([SALES, OPERATION, AGENT, AGENT_BOSS])">
        <a-input v-model:value.trim="queryFields.customerId" placeholder="请输入客户ID" allow-clear />
      </a-form-item>
      <a-form-item name="customerName" label="客户名称">
        <a-input placeholder="请输入客户名称" allow-clear v-model:value.trim="queryFields.customerName"></a-input>
      </a-form-item>
      <a-form-item name="industryId" label="行业">
        <industry-cascader
          v-model:industry-id="industryId"
          :industry-list="industryList"
          @change="handleIndustryChange"
        />
      </a-form-item>
    </QueryFilter>
    <Divider />
    <table-toolbar title="推广列表">
      <export-excel-group
        group
        :loading="excelLoading"
        :col="columns"
        :data="tableData"
        v-permission="[OPERATION]"
        @on-export="handleExportExcel"
        @on-export-all="handleExportExcelAll"
        @on-custom-export="handleCustomExportExcel"
      >
        <a-menu-item key="1">
          <file-text-outlined />
          导出本页计划
        </a-menu-item>
        <a-menu-item key="2">
          <file-text-outlined />
          导出全部计划
        </a-menu-item>
        <a-menu-item key="3">
          <file-search-outlined />
          导出全部创意
        </a-menu-item>
      </export-excel-group>
    </table-toolbar>
    <a-table
      table-layout="fixed"
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      :columns="columns"
      :data-source="tableData"
      :scroll="{ x: 1000 }"
      @change="handleTableChange"
    >
      <template #bodyCell="{ record, column, text }">
        <template v-if="column.key === 'areas'">
          <area-popover ellipsis :areas="text" :product-id="record.productId" />
        </template>
        <template v-if="column.key === 'orderId'">
          <span class="cursor-pointer" v-clipboard="record.orderId" v-clipboard:success="copySuccess">{{
            record.orderId
          }}</span>
        </template>
        <template v-if="column.key === 'serviceUserName'">
          <span class="cursor-pointer" v-clipboard="record.serviceUserName" v-clipboard:success="copySuccess">{{
            record.serviceUserName
          }}</span>
        </template>
        <template v-if="column.key === 'orderWordsStr'">
          <a-tooltip placement="topLeft">
            <template #title>
              {{ record.orderWordsStr }}
            </template>
            <span class="cursor-pointer" v-clipboard="record.orderWordsStr" v-clipboard:success="copySuccess">{{
              record.orderWordsStr
            }}</span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'operate'">
          <a-button type="primary" :disabled="shouldOffline(record)" @click="handlePromotion(record)"
            >编辑创意</a-button
          >
          <a-dropdown v-if="!hasPermission(CUSTOMER)">
            <template #overlay>
              <a-menu @click="handleMenuClick($event, record)">
                <a-menu-item key="1" :disabled="shouldOffline(record)" v-if="hasPermission([OPERATION])">
                  改词
                </a-menu-item>
                <!-- <div v-if="column.key.thType === 1">显示</div> -->
                <a-menu-item
                  key="2"
                  :disabled="shouldOffline(record) || record.productId == ProductEnum.HJBW"
                  v-if="
                    (hasPermission([SALES, AGENT, AGENT_BOSS, OPERATION, ADMIN]) && record.thType !== 1) ||
                    record.productId === 9 ||
                    record.productId === 10
                  "
                >
                  <!-- 增词 -->
                  {{
                    record.productId === 10 ||
                    record.productId === 7 ||
                    record.productName === '词包特惠版' ||
                    record.productId === 9
                      ? '精准词包工具'
                      : '增词'
                  }}
                </a-menu-item>

                <a-menu-item
                  key="7"
                  :disabled="shouldOffline(record) || record.productId == ProductEnum.HJBW"
                  v-if="
                    (hasPermission([SALES, AGENT, AGENT_BOSS, OPERATION, ADMIN]) &&
                      record.thType !== 1 &&
                      record.productName === '词包特惠版') ||
                    record.productId === 9 ||
                    record.productId === 10 ||
                    record.productId === 7
                  "
                  @click="elxietd(record.orderId)"
                >
                  词包表格上传
                </a-menu-item>

                <a-sub-menu title="迁框" v-if="hasPermission([OPERATION])">
                  <!-- <a-menu-item key="3" :disabled="record.serviceStatus !== ServiceStatusEnum.Launch">
                    删除重上
                  </a-menu-item> -->
                  <a-menu-item key="4"> 更换账号 </a-menu-item>
                </a-sub-menu>

                <a-menu-item
                  key="8"
                  :disabled="shouldOffline(record) || record.productId == ProductEnum.HJBW"
                  v-if="(record.productId === 10 || record.productId === 7) && hasPermission([OPERATION])"
                >
                  开启配图额度
                </a-menu-item>

                <a-menu-item
                  key="9"
                  :disabled="shouldOffline(record) || record.productId == ProductEnum.HJBW"
                  v-if="(record.productId === 10 || record.productId === 7) && hasPermission([OPERATION])"
                >
                  修改增词额度
                </a-menu-item>
                <a-menu-divider v-if="hasPermission([OPERATION])"></a-menu-divider>
                <a-menu-item key="5" :disabled="!shouldPausePlan(record)" v-if="hasPermission([OPERATION])">
                  暂停投放
                </a-menu-item>
                <a-menu-item key="6" :disabled="!shouldOpenPlan(record)" v-if="hasPermission([OPERATION])">
                  开启投放
                </a-menu-item>
                <a-menu-item
                  key="7"
                  @click="(timeVisible = true), (timeRange = record.onLinePeriod), (timeOrderId = record.orderId)"
                  v-if="hasPermission([OPERATION])"
                >
                  修改时间段
                </a-menu-item>
              </a-menu>
            </template>
            <a-button class="ml-2">
              更多操作
              <DownOutlined />
            </a-button>
          </a-dropdown>
        </template>
      </template>
    </a-table>
    <word-gift-kind
      ref="WordGiftKindRef"
      v-model:show="visible"
      v-model:active-key="activeKey"
      v-model:gift-fields="giftFields"
      v-model:composable-state="composableState"
      v-model:ConfigurationGift="ConfigurationGift"
      :Gift="Gift"
      :submitting="submitting"
      :record="currentRecord"
      @on-add="handleGiftWordAdd"
      @on-submit="handleGiftWordSubmit"
      @on-hide="resetGiftWordData"
      @loadPromotionList="loadPromotionList"
    />
    <CbWordGiftKind
      ref="WordGiftKindRef"
      :messageidis="parentMessage"
      v-model:show="CbVisible"
      v-model:active-key="activeKey"
      v-model:gift-fields="giftFields"
      v-model:composable-state="composableState"
      v-model:ConfigurationGift="ConfigurationGift"
      v-model:CbNum="CbNum"
      :Gift="Gift"
      :submitting="submitting"
      :record="currentRecord"
      @on-add="handleGiftWordAdd"
      @on-submit="handleGiftWordSubmit"
      @on-hide="resetGiftWordData"
      @loadPromotionList="loadPromotionList"
    />
    <a-modal v-model:visible="opendds" @ok="handleOk" style="width: 800px; height: 500px">
      <div class="kkkisdjxasd">
        <h3 style="width: 300px">特惠版剩余拓词数量： {{ openddstitled }}</h3>
        <div style="margin-left: 340px; width: 100px">
          <a href="http://bw.e-baixing.com/files/thTypeMode.xlsx">
            <a-button type="primary">模板下载</a-button>
          </a>
        </div>
      </div>
      <a-upload :disabled="openddstitled < 0" :customRequest="handleUpload" name="file" @change="handleChange">
        <a-button>
          <upload-outlined></upload-outlined>
          上传文件
        </a-button>
      </a-upload>
      <div style="margin-top: 10px">
        <span style="color: green">上传完成，成功词数:</span>
        <span style="margin-left: 10px">{{ successNumberitem }}条</span>
      </div>
      <div style="margin-top: 10px" v-if="errorAbcListitem.length != 0">
        <h4 style="color: red">该词不是特惠版ABC拓词:</h4>
        <span v-for="(v, i) in errorAbcListitem" :key="i" style="margin: 0 10px">
          {{ v }}
        </span>
      </div>
      <div style="margin-top: 10px" v-if="errorIsSoldListitem.length != 0">
        <h4 style="color: red">以下已售词需更换:</h4>
        <span v-for="(v, i) in errorIsSoldListitem" :key="i" style="margin: 0 10px">
          {{ v }}
        </span>
      </div>
    </a-modal>
  </BaseContainer>
  <div>
    <a-modal v-model:visible="visibleedxg" title="修改配词额度" @ok="handleOkedxg">
      <p style="margin-left: 10px">原来词数: {{ peicinum }}</p>
      <a-form :model="formStateedxg" name="basic">
        <a-form-item label="修改词数" name="pcNumber" :rules="[{ required: true, message: '修改额度不能为空' }]">
          <a-input v-model:value="formStateedxg.pcNumber" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
  <template>
    <div>
      <a-modal v-model:visible="accountVisible" title="更改账号" :width="800">
        <div>
          <a-form :model="formAccount" name="basic">
            <a-form-item label="新账号" name="account" required>
              <a-input v-model:value="formAccount.account" />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-table :columns="accountcolumns" :data-source="accountdata" bordered>
            <template #bodyCell="{ column, text }">
              <template v-if="column.key === 'upload'">
                <!-- <CheckCircleFilled class="success" v-if="text === BatchStatusEnum.Success"></CheckCircleFilled>
          <CloseCircleOutlined class="failed" v-else-if="text === BatchStatusEnum.Failed"></CloseCircleOutlined>
          <LoadingOutlined class="loading" v-else-if="text === BatchStatusEnum.Loading"></LoadingOutlined>
          <span v-else>等待</span> -->
              </template>
              <template v-if="column.key === 'message'">
                <a-tooltip>
                  <template #title>{{ text || '--' }}</template>
                  {{ text || '--' }}
                </a-tooltip>
              </template>
            </template>
          </a-table>
        </div>
        <template #footer>
          <a-button key="back" @click="accountVisible = false">关闭</a-button>
          <a-button key="submit" type="primary" v-if="buttonVisible" :loading="transferLoading" @click="accountOk"
            >确定</a-button
          >
        </template>
      </a-modal>
    </div>
  </template>
  <PromotionUpdateTime v-model:visible="timeVisible" :value="timeRange" :orderId="timeOrderId" @refresh="refreshFn">
  </PromotionUpdateTime>
</template>

<script lang="ts" setup name="Promotion">
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import { computed, onActivated, onMounted, reactive, ref, defineComponent, watch } from 'vue'
import { formatDate, toLabelValue } from '@/utils'
import { message, Modal, type TableProps } from 'ant-design-vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import ExportExcelGroup from '@/components/export-excel-group/index.vue'
import { hasPermission } from '@/utils/permission'
import { compact, isNil } from 'lodash-es'
import { useMainStore } from '@/store/useMainStore'
import BaseContainer from '@/components/base-container/index.vue'
import QueryFilter from '@/components/query-filter/index.vue'
import getPromotionList, { getPromotionListWithAll, type PromotionQuery } from '@/services/promotion/getPromotionList'
import { OrderOperateEnum, usePromotionStore } from '@/store/usePromotionStore'
import { useCategory } from '@/hooks/useCategotry'
import Divider from '@/components/divider/index.vue'
import WordGiftKind from '@/views/promotion/components/WordGiftKind.vue'
import CbWordGiftKind from '@/views/promotion/components/CbWordGiftKind.vue'
import type { FreeWord } from '@/services/promotion/updateFreeWord'
import updateFreeWord from '@/services/promotion/updateFreeWord'
import checkOnlineActivity from '@/services/promotion/checkOnlineActivity'
import AreaPopover from '@/components/area-popover/index.vue'
import type { Promotion } from '@/core/interfaces/promotion'
import { AuthEnum } from '@/core/enums/auth'
import type { Order } from '@/core/interfaces/order'
import { ProductEnum } from '@/core/enums/platform'
import { ActivityTypeEnum, WordTypeEnum } from '@/core/enums/type'
import { ServiceApproveStatusEnum, ServiceStatusEnum } from '@/core/enums/status'
import { ServiceApproveStatusKeyMap, ServiceStatusKeyMap } from '@/core/mapper/status'
import { DownOutlined, FileSearchOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons-vue'
import migrateAccount from '@/services/promotion/migrateAccount'
import migrateRemove from '@/services/promotion/migrateRemove'
import { allCreativeCols, getPromotionAllCreative } from '@/services/promotion/getPromotionAllCreative'
import IndustryCascader from '@/components/industry-cascader/index.vue'
import getIndustryList from '@/services/order/getIndustryList'
import { transformMovedStatus } from '@/views/promotion/utils'
import launchPlan from '@/services/promotion/launchPlan'
import pausePlan from '@/services/promotion/pausePlan'
import type { ComposableState } from '@/views/promotion/interface'
import { GiftKindEnum, type CbNumType } from '@/views/promotion/interface'
import type { ConfigurationGiftType } from '@/services/promotion/editConfigurationGift'
import type { OnlineActivityInfo } from '@/services/promotion/checkOnlineActivity'
import residueNumberdeFnis from '@/services/account-management/residueNumberiteus'
import type { UploadChangeParam } from 'ant-design-vue'
import openOneImgQuota from '@/services/account-management/openOneImgQuota.ts'
import getOrderCombinedWordNumSum from '@/services/account-management/getOrderCombinedWordNumSum'
import updateOrderCombinedWordNumSum from '@/services/account-management/updateOrderCombinedWordNumSum'
import getAllUnitByAdId from '@/services/account-management/getAllUnitByAdId'
import transferAccountNumber from '@/services/account-management/transferAccountNumber'
import transferStart from '@/services/account-management/transferStart'
import PromotionUpdateTime from '@/views/promotion/components/PromotionUpdateTime.vue'

const router = useRouter()
const mainStore = useMainStore()
const promotionStore = usePromotionStore()
const { SALES, AGENT, AGENT_BOSS, OPERATION, ADMIN, CUSTOMER } = AuthEnum
const WordGiftKindRef = ref<InstanceType<typeof WordGiftKind>>()
const openddstitled = ref(null)
const opendds = ref(false)

const formStateedxg = reactive({
  pcNumber: ''
})
const formAccount = reactive({
  account: ''
})

const accountdata = ref([])
const accountcolumns = [
  // {
  //   title: 'Name',
  //   dataIndex: 'name'
  // },
  // {
  //   title: '上传',
  //   dataIndex: 'upload',
  //   key: 'upload',
  //   width: '80px'
  // },
  {
    title: '提示',
    dataIndex: 'message',
    key: 'message',
    ellipsis: true
  },
  {
    title: '创意Id',
    className: 'id',
    dataIndex: 'id'
  },
  {
    title: '关键词Id',
    dataIndex: 'orderWordId'
  },
  {
    title: '关键词',
    dataIndex: 'word'
  }
]
const handleOk = (e) => {
  opendds.value = false
  location.reload()
}
const [, openOneImgQuotaFn] = openOneImgQuota()
// 监听opendds的变化
watch(opendds, (newVal, l) => {
  if (l) {
    location.reload()
  }
})
// 上传文件
const orderIditemius = ref()
const handleChange = (info) => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList)
  }
  // if (info.file.status === 'done') {
  //   message.success(`${info.file.name} file uploaded successfully`)
  // } else if (info.file.status === 'error') {
  //   message.error(`${info.file.name} file upload failed.`)
  // }
}

const visibleedxg = ref(false)
const accountVisible = ref(false)
const errorAbcListitem = ref([])

const errorIsSoldListitem = ref([])
const successNumberitem = ref(0)

const handleUpload = async (option) => {
  const formData = new FormData()
  formData.append('file', option.file) // 添加文件
  // token: JSON.parse(localStorage.getItem('token') as string),
  // 在这里添加你的额外参数
  formData.append('orderId', orderIditemius.value) // 假设这是用户的ID
  try {
    //  action="http://180.76.39.111:8885/api/v1/upThTypeExcel"
    // const response = await fetch('http://180.76.39.111:8885/api/v1/upThTypeExcel', {
    //   method: 'POST',
    //   body: formData,
    //   headers: {
    //     token: JSON.parse(localStorage.getItem('token') as string),
    //     userId: mainStore.userId
    //   }
    // })
    const res = import.meta.env.VITE_API_URL
    const response = await fetch(`${res}/api/v1/upThTypeExcel`, {
      method: 'POST',
      body: formData,
      headers: {
        token: JSON.parse(localStorage.getItem('token') as string),
        userId: mainStore.userId
      }
    })

    if (!response.ok) {
      throw new Error('Network response was not ok')
    }
    const data = await response.json()
    // 处理响应数据，比如更新 fileList
    if (data.code === 0) {
      errorAbcListitem.value = data.data.errorAbcList
      errorIsSoldListitem.value = data.data.errorIsSoldList
      successNumberitem.value = data.data.successNumber

      if (data.data.errorAbcList.length === 0 && data.data.errorIsSoldList.length === 0) {
        message.success('上传成功')
        opendds.value = false
      } else {
        message.success('请重新编辑上传')
        // opendds.value = false
      }
    } else {
      message.error(data.msg)
    }
  } catch (error) {
    console.error('Error uploading file: 报错了接口没走', error)
  }
}

const fileList = ref([])
const defaultQueryFields = () => ({
  orderId: undefined,
  sellerId: mainStore.sellerId,
  proxyId: mainStore.proxyId,
  customerId: mainStore.customerId,
  serviceApproveStatus: ServiceApproveStatusEnum.All,
  serviceStatus: ServiceStatusEnum.All,
  keyword: '',
  industryCode: undefined,
  customerName: ''
})

const queryFields = reactive<Partial<PromotionQuery>>(defaultQueryFields())
const defaultFormFields = () => ({
  wordNum: 0,
  freeWords: []
})
const defaultComposableState = () => ({
  result: [],
  combinedWordNum: 0,
  word: '',
  keyword: [],
  areas: [],
  suffix: []
})
const activeKey = ref(GiftKindEnum.Gift)
const visible = ref(false)
const CbVisible = ref(false)
const giftFields = ref<{ wordNum: number; freeWords: FreeWord[] }>(defaultFormFields())
const composableState = ref<ComposableState>(defaultComposableState())
const currentRecord = ref<Partial<Promotion>>({})
const approveStatusOptions = ref(toLabelValue(ServiceApproveStatusKeyMap))
const serviceStatusOptions = ref(toLabelValue(ServiceStatusKeyMap))
const industryId = ref<number | undefined>()

const [tableData, fetchPromotionList, loading] = getPromotionList()
const [, fetchPromotionListWithAll, excelLoading] = getPromotionListWithAll()
const [, fetchPromotionAllCreative] = getPromotionAllCreative()
const [, submitFreeWord, submitting] = updateFreeWord()
const [, fetchOnlineActivity] = checkOnlineActivity()
const [, fetchMigrateAccount] = migrateAccount()
const [, fetchMigrateRemove] = migrateRemove()
const [, fetchLaunchPlan] = launchPlan()
const [, fetchPausePlan] = pausePlan()
const [, getOrderCombinedWordNumSumFn] = getOrderCombinedWordNumSum()
const [, updateOrderCombinedWordNumSumFn] = updateOrderCombinedWordNumSum()
const [, getAllUnitByAdIdFn] = getAllUnitByAdId()
const [industryList, fetchIndustryList] = getIndustryList()

const [, transferAccountNumberFn] = transferAccountNumber()
const [, transferStartFn] = transferStart()
const [, residueNumberdeFn] = residueNumberdeFnis()
function shouldOffline(record: Promotion) {
  const { Offline, Launched } = ServiceStatusEnum
  return [Offline, Launched].includes(record.serviceStatus)
}

function shouldPausePlan(record: Promotion) {
  const { Launch } = ServiceStatusEnum
  return Launch === record.serviceStatus
}

function shouldOpenPlan(record: Promotion) {
  const { Before_Launch } = ServiceStatusEnum
  return Before_Launch === record.serviceStatus
}
const columns = computed<TableProps['columns']>(() => {
  return compact([
    {
      title: '词包ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: '120px'
    },
    {
      title: '产品',
      dataIndex: 'productName',
      key: 'productName',
      width: '150px'
    },
    {
      title: '关键词',
      dataIndex: 'orderWordsStr',
      key: 'orderWordsStr',
      width: '150px',
      ellipsis: true
    },
    {
      title: '行业',
      dataIndex: 'industryName',
      key: 'industryName',
      width: '150px',
      customRender: ({ text }) => {
        if (!text) {
          return '--'
        }
        return text
      }
    },
    hasPermission([SALES, AGENT, AGENT_BOSS, OPERATION, ADMIN]) && {
      title: '客户名称',
      dataIndex: 'customerName',
      key: 'customerName',
      width: '200px'
    },
    hasPermission([OPERATION]) && {
      title: '投放账号',
      dataIndex: 'serviceUserName',
      key: 'serviceUserName',
      width: '200px'
    },
    {
      title: '审核状态',
      dataIndex: 'serviceApproveStatus',
      key: 'serviceApproveStatus',
      width: '150px',
      customRender: ({ record }: { record: Promotion }) => {
        return transformMovedStatus(record)
      }
    },
    {
      title: '上线状态',
      dataIndex: 'serviceStatus',
      key: 'serviceStatus',
      width: '150px',
      customRender: ({ text }: { text: ServiceStatusEnum }) => {
        return ServiceStatusKeyMap[text]
      }
    },
    {
      title: '投放时长',
      dataIndex: 'days',
      key: 'days',
      width: '150px'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: '180px',
      customRender: ({ text }: { text: string }) => {
        return formatDate(text)
      }
    },
    {
      title: '投放开始时间',
      dataIndex: 'serviceTime',
      key: 'serviceTime',
      width: '200px',
      customRender: ({ text }: { text: string }) => {
        if (text) {
          return formatDate(text)
        } else {
          return '--'
        }
      }
    },
    {
      title: '投放结束时间',
      dataIndex: 'expireTime',
      key: 'expireTime',
      width: '200px',
      customRender: ({ text }: { text: string }) => {
        if (text) {
          return formatDate(text)
        } else {
          return '--'
        }
      }
    },
    {
      title: '剩余天数',
      dataIndex: 'remainDays',
      key: 'remainDays',
      width: '120px'
    },
    {
      title: '投放时间段',
      dataIndex: 'onLinePeriod',
      key: 'onLinePeriod',
      width: '150px',
      customRender: ({ record, text }: { record: Order; text: string }) => {
        return text || '--'
      }
    },
    {
      title: '投放区域',
      dataIndex: 'areas',
      key: 'areas',
      width: '150px',
      customRender: ({ record, text }: { record: Order; text: string }) => {
        if (record.productId === ProductEnum.CiBao || record.productId === ProductEnum.CBYXB) {
          return '全国'
        } else {
          return text || '--'
        }
      }
    },

    hasPermission([OPERATION]) && {
      title: '代理商名称',
      dataIndex: 'proxyName',
      key: 'proxyName',
      width: '200px'
    },
    hasPermission([OPERATION]) && {
      title: '归属大区',
      dataIndex: 'proxyOrganize',
      key: 'proxyOrganize',
      width: '200px'
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      width: '230px'
    }
  ])
})

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

function getCampaignId(record: Promotion) {
  return record.pcCampaignId || record.wapCampaignId || record.pcWapCampaignId
}

async function loadPromotionList() {
  const [err, res] = await fetchPromotionList({
    pageSize: pagination.pageSize,
    pageNum: pagination.current,
    ...queryFields,
    orderId: queryFields.orderId || 0,
    sellerId: mainStore.sellerId,
    industryCode: queryFields.industryCode || 0
  })

  if (!err) {
    pagination.total = res.data.data.totalSize
  }
}

function resetOrderList() {
  Object.assign(queryFields, defaultQueryFields())
  industryId.value = undefined
  pagination.pageSize = 15
  pagination.current = 1
  loadPromotionList()
}

function queryOrderList() {
  pagination.pageSize = 15
  pagination.current = 1
  loadPromotionList()
}

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadPromotionList()
}
const visiblekaiqi = ref(false)
const cbworditemiis = ref(false)
const adId = ref(0)
const peicinum = ref(0)
const adIdiusyds = ref(0)
async function handleMenuClick(e: any, record: Promotion) {
  if (e.key === '1') {
    handlePromotion(record, OrderOperateEnum.editable)
  } else if (e.key === '2') {
    handleFreeWord(record)
  } else if (e.key === '3') {
    handleRemoveMigration(record)
  } else if (e.key === '4') {
    // handleAccountMigration(record)
    accountVisible.value = true
    buttonVisible.value = true
    formAccount.account = ''
    // console.log(record.id, '切换场合')
    adId.value = record.id
    let [err, res] = await getAllUnitByAdIdFn({
      adId: record.id
    })
    if (!err) {
      accountdata.value = res.data.data
    }
    console.log(res.data.data, '切换场合')
  } else if (e.key === '5') {
    handlePausePlan(record)
  } else if (e.key === '6') {
    handleLaunchPlan(record)
  } else if (e.key === '8') {
    Modal.confirm({
      title: '提示',
      content: '确定要开启配图额度吗？',
      async onOk() {
        let [err, res] = await openOneImgQuotaFn({
          adId: record.id
        })
        if (!err) {
          message.success('开启成功')
        }
      }
    })
  } else if (e.key === '9') {
    adIdiusyds.value = record.id
    let [err, res] = await getOrderCombinedWordNumSumFn({ adId: record.id })
    if (!err) {
      peicinum.value = res.data.data
    }
    visibleedxg.value = true
  }
  // const showModalkaiqi = () => {

  // };

  // else if (e.key === '7') {
  //   console.log(e, '特惠extex版本')
  //   opendds.value = true

  //    let res= await residueNumberdeFn()

  //   //  orderId
  //   // handleFreeWorddsd(cbworditemiis.value)
  //   // handleLaunchPlan(record)
  // }
}
const transferLoading = ref(false)
const buttonVisible = ref(true)
const accountOk = async () => {
  try {
    transferLoading.value = true
    // 遍历 accountdata.value 中的每一项
    let [errA, resA] = await transferAccountNumberFn({
      adId: adId.value,
      serviceUserName: formAccount.account
    })
    if (!errA) {
      // 如果满足条件，再调用接口 B
      // if (item.serviceUserName === formaccount.account) {}
      for (const item of accountdata.value) {
        let [err, res] = await transferStartFn({
          adId: adId.value,
          clientType: item.clientType,
          id: item.id
        })
        if (err) {
          item.message = err.message
        } else {
          item.message = res.data.data
        }
      }
    }
  } catch (error) {
    console.error('执行过程中出错:', error)
  } finally {
    transferLoading.value = false
    buttonVisible.value = false
  }
}
const handleOkedxg = async () => {
  let pcNumber = formStateedxg.pcNumber

  // 使用Number()函数转换
  let number = Number(pcNumber)

  // 或者使用一元加号
  let numberd = +pcNumber

  let [err, res] = await updateOrderCombinedWordNumSumFn({
    adId: adIdiusyds.value,
    pcNumber: numberd
  })
  if (!err) {
    message.success(res.data.data)
  }
  formStateedxg.pcNumber = ''
  visibleedxg.value = false
}
const elxietd = async (id) => {
  opendds.value = true
  orderIditemius.value = id
  let [, res] = await residueNumberdeFn({
    orderId: id
  })
  if (res.data.code === 0) {
    openddstitled.value = res.data.data
  }
  errorAbcListitem.value = []

  errorIsSoldListitem.value = []
  successNumberitem.value = 0
  // console.log(res, '剩余的词包数量和数据')
}
function handlePausePlan(record: Promotion) {
  Modal.confirm({
    title: '提示',
    content: '暂停后计划将在百度侧暂停投放，落袋暂停，投放时间都将暂停，是否确定暂停？',
    async onOk() {
      const [err, res] = await fetchPausePlan({
        orderId: record.orderId
      })

      if (!err) {
        message.success(res.data.msg)
        loadPromotionList()
      } else {
        message.error(err.message)
      }
    }
  })
}
function handleLaunchPlan(record: Promotion) {
  Modal.confirm({
    title: '提示',
    content: '开启后计划将在百度侧开启投放同时开启落袋，计划投放时间开始扣除，是否确定开启？',
    async onOk() {
      const [err, res] = await fetchLaunchPlan({
        orderId: record.orderId
      })

      if (!err) {
        message.success(res.data.msg)
        loadPromotionList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handleRemoveMigration(record: Promotion) {
  const campaignId = getCampaignId(record)
  if (isNil(campaignId) || campaignId === 0) {
    return message.error('当前计划未创建，该功能无法使用')
  }

  Modal.confirm({
    title: '提示',
    content: '确定要删除重上吗？',
    async onOk() {
      const [err, res] = await fetchMigrateRemove({
        campaignId
      })

      if (!err) {
        message.success(res.data.msg)
        await loadPromotionList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handleAccountMigration(record: Promotion) {
  const campaignId = getCampaignId(record)

  if (isNil(campaignId) || campaignId === 0) {
    return message.error('当前计划未创建，该功能无法使用')
  }

  Modal.confirm({
    title: '提示',
    content: '确定要更换账号吗？',
    async onOk() {
      const [err, res] = await fetchMigrateAccount({
        campaignId
      })
      if (!err) {
        message.success(res.data.msg)
        await loadPromotionList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function handlePromotion(record: Promotion, operate: OrderOperateEnum = OrderOperateEnum.normal) {
  if (shouldOffline(record)) {
    return message.error('推广已下线')
  }

  promotionStore.setOrderDetailOperate(operate)

  router.push({
    name: 'promotion-detail',
    query: {
      adId: record.id
    }
  })
}

const defaultConfigurationGift = () => ({
  combinedWordNumSum: 0,
  wordNumSum: 0,
  orderId: undefined
})

const ConfigurationGift = ref<ConfigurationGiftType>(defaultConfigurationGift())

const defaultCbNum = () => ({
  pcNumber: 0,
  wapNumber: 0,
  orderId: undefined
})

const CbNum = ref<CbNumType>(defaultCbNum())

const Gift = ref<OnlineActivityInfo>()
const parentMessage = ref(0)

function addis() {
  parentMessage.value = 1
}

async function handleFreeWord(record: Promotion) {
  if (shouldOffline(record)) {
    return message.error('推广已下线')
  }
  ConfigurationGift.value.combinedWordNumSum = 0
  ConfigurationGift.value.wordNumSum = 0
  ConfigurationGift.value.orderId = record.orderId
  CbNum.value.orderId = record.orderId
  //
  //
  const isSpecialProduct = [
    ProductEnum.CiBao,
    ProductEnum.CBYXB,
    ProductEnum.CBTEH,
    ProductEnum.WbBao,
    ProductEnum.DFBEN
  ].includes(record.productId)

  const isZiTianSpecial = record.productId === 9 && record.ziTianCode === 1

  if (isSpecialProduct && !isZiTianSpecial) {
    activeKey.value = GiftKindEnum.Composable
    CbVisible.value = true

    if ([ProductEnum.CBTEH, ProductEnum.WbBao, ProductEnum.DFBEN].includes(record.productId)) {
      localStorage.setItem('teihui', 'true')
      addis()
    } else {
      localStorage.removeItem('teihui')
      parentMessage.value = 0
    }
  } else {
    visible.value = true
  }

  giftFields.value = defaultFormFields()
  currentRecord.value = record
  const [err, res] = await fetchOnlineActivity({
    type: ActivityTypeEnum.Word,
    orderId: record.orderId,
    giftType: activeKey.value
  })

  if (!err) {
    Gift.value = res.data.data
    CbNum.value.pcNumber = res.data.data.pcNumber || 0
    CbNum.value.wapNumber = res.data.data.wapNumber || 0
    ConfigurationGift.value.combinedWordNumSum = res.data.data.combinedWordNumSum || 0
    ConfigurationGift.value.wordNumSum = res.data.data.wordNumSum || 0
    giftFields.value.wordNum = res.data.data.wordNum
    composableState.value.combinedWordNum = res.data.data.combinedWordNum
  } else {
    message.error(err.message)
    giftFields.value.wordNum = 0
    composableState.value.combinedWordNum = 0
  }

  if (giftFields.value.wordNum > 0) {
    await handleGiftWordAdd()
  }
}

function handleGiftWordAdd() {
  const { BW, BWYXB } = useCategory(currentRecord.value.productId)

  giftFields.value.freeWords.push({
    name: '',
    clientType: BW || BWYXB ? currentRecord.value.clientType : undefined,
    orderNo: currentRecord.value.orderNo!,
    orderId: currentRecord.value.orderId!,
    versionType: currentRecord.value.versionType!,
    type: WordTypeEnum.Zxzc,
    updateUserId: mainStore.userId!,
    giftType: GiftKindEnum.Gift
  })
}

function makeComposableData() {
  if (composableState.value.result[0].name) {
    return composableState.value.result.map((item) => {
      return {
        name: item.name,
        clientType: item.type,
        orderNo: currentRecord.value.orderNo!,
        orderId: currentRecord.value.orderId!,
        versionType: currentRecord.value.versionType!,
        type: WordTypeEnum.Zhzc,
        updateUserId: mainStore.userId!,
        giftType: activeKey.value
      }
    })
  } else {
    return composableState.value.result.map((item) => {
      return {
        name: item,
        clientType: currentRecord.value.clientType,
        orderNo: currentRecord.value.orderNo!,
        orderId: currentRecord.value.orderId!,
        versionType: currentRecord.value.versionType!,
        type: WordTypeEnum.Zhzc,
        updateUserId: mainStore.userId!,
        giftType: activeKey.value
      }
    })
  }
}

function composableWordSubmit() {
  let iis = localStorage.getItem('teihui')

  Modal.confirm({
    title: '提示',
    content: iis ? '是否提交精准词包' : '是否提交组合词？',
    async onOk() {
      const [err] = await submitFreeWord(makeComposableData())

      if (!err) {
        visible.value = false
        CbVisible.value = false
        resetGiftWordData()
        message.success('组合词添加成功')
        loadPromotionList()
      } else {
        message.error(err.message)
      }
    }
  })
}

function giftWordSubmit() {
  Modal.confirm({
    title: '提示',
    content: '是否提交赠词？',
    async onOk() {
      const [err, res] = await submitFreeWord(giftFields.value.freeWords)

      if (!err) {
        visible.value = false
        resetGiftWordData()
        message.success(res.data.msg || '添加赠词成功')
        loadPromotionList()
      } else {
        message.error(err.message)
      }
    }
  })
}

async function handleGiftWordSubmit() {
  if (activeKey.value === GiftKindEnum.Composable) {
    composableWordSubmit()
  } else {
    giftWordSubmit()
  }
}

function resetGiftWordData() {
  activeKey.value = GiftKindEnum.Gift
  giftFields.value.freeWords = []
  WordGiftKindRef.value?.resetFormFields()
  const resetData = defaultComposableState()
  resetData.combinedWordNum = composableState.value.combinedWordNum
  composableState.value = resetData
}

function handleExportExcel(exportExcel: Function) {
  exportExcel(`推广列表${Date.now()}`)
}

async function handleExportExcelAll(exportExcel: Function) {
  const [err, res] = await fetchPromotionListWithAll({
    ...defaultQueryFields(),
    pageNum: 1,
    pageSize: 9999999,
    orderId: queryFields.orderId || 0,
    sellerId: mainStore.sellerId,
    industryCode: queryFields.industryCode || 0
  })

  if (err) {
    message.error(err.message || '导出失败')
  } else {
    exportExcel(`推广列表${Date.now()}`, {}, res.data.data.ads)
  }
}

async function handleCustomExportExcel(key: string, exportExcel: Function) {
  if (key === '3') {
    const [err, res] = await fetchPromotionAllCreative()

    if (!err) {
      exportExcel(`创意列表${Date.now()}`, {}, res.data.data, allCreativeCols)
    } else {
      message.error(err.message)
    }
  }
}

function handleIndustryChange() {
  queryFields.industryCode = industryList.value.find((item) => item.id === industryId.value)?.code
}

function copySuccess() {
  message.success('复制成功')
}
const mingz = ref('')
function add() {
  mingz.value = localStorage.getItem('productId')
}

const timeVisible = ref(false)
const timeRange = ref('')
const timeOrderId = ref()

const refreshFn = () => {
  timeRange.value = ''
  timeOrderId.value = ''
  loadPromotionList()
}

onMounted(() => {
  add()
  fetchIndustryList()
})

onBeforeRouteLeave((to) => {
  if (to.name !== 'promotion-detail') {
    pagination.current = 1
  }
})
//
onActivated(() => {
  loadPromotionList()
})
</script>

<style scoped>
.kkkisdjxasd {
  display: flex;
  align-items: center;
  margin: 0 10px;
  margin-bottom: 20px;
  /* justify-content: center; */
  /* height: 100%; */
}

.a-modal-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
  /* 控制按钮之间的间距 */
}

.a-modal-footer .a-button {
  width: 100px;
  /* 控制按钮宽度 */
}
</style>
